package cn.edu.scau.cmi.linzhanyi.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateCRUD {
	private static SessionFactory sf = new Configuration().configure().buildSessionFactory();
	
	public static void createStudent(Student student) {
		Session s = sf.openSession();
        s.beginTransaction();
        s.save(student);
        s.getTransaction().commit();
        s.close();
	}
	public static void deleteStudent(Integer  id) {
		Session s = sf.openSession();
        s.beginTransaction();
        Student student =(Student) s.get(Student.class, id);
        s.delete(student);
        s.getTransaction().commit();
        s.close();
	}
	public static void updateStudent(Integer  id,String name) {
		Session s = sf.openSession();
        s.beginTransaction();
        Student student =(Student) s.get(Student.class, id);
        if (student!=null) {
        	student.setName(name);
            s.update(student);
		}
        
        s.getTransaction().commit();
        s.close();
	}
	public static void updateStudent(Integer  id,Teacher tutor) {
		Session s = sf.openSession();
        s.beginTransaction();
        Student student =(Student) s.get(Student.class, id);
        if (student!=null) {
        	student.setTutor(tutor);
            s.update(student);
		}
        
        s.getTransaction().commit();
        s.close();
	}
	public static List<Student> checkStudent() {
		Session s = sf.openSession();
        s.beginTransaction();
        String sql = "select * from student";        
        Query q= s.createSQLQuery(sql).addEntity(Student.class);    
        List<Student> list= q.list();
        s.getTransaction().commit();
        s.close();
        return list;
	}
	public static void createTeacher(Teacher teacher) {
		Session s = sf.openSession();
        s.beginTransaction();
        s.save(teacher);
        s.getTransaction().commit();
        s.close();
	}
	public static void deleteTeacher(Integer  id) {
		Session s = sf.openSession();
        s.beginTransaction();
        Teacher teacher =(Teacher) s.get(Teacher.class, id);
        s.delete(teacher);
        s.getTransaction().commit();
        s.close();
	}
	public static void updateTeacher(Integer  id,String name) {
		Session s = sf.openSession();
        s.beginTransaction();
        Teacher teacher =(Teacher) s.get(Teacher.class, id);
        if (teacher!=null) {
        	teacher.setName(name);
            s.update(teacher);
		}
        
        s.getTransaction().commit();
        s.close();
	}
	public static List<Teacher> checkTeacher() {
		Session s = sf.openSession();
        s.beginTransaction();
        String sql = "select * from teacher";        
        Query q= s.createSQLQuery(sql).addEntity(Teacher.class);
        List<Teacher> list= q.list();
        s.getTransaction().commit();
        s.close();
        return list;
	}
}
